package logic

import (
	"context"
	"errors"
	"fmt"
	"math/rand"
	"short-video-manager/models/cache"
	"short-video-manager/models/mysql"
	"short-video-manager/pkg"

	"short-video-manager/videorpc/internal/svc"
	"short-video-manager/videorpc/videorpc"

	"github.com/zeromicro/go-zero/core/logx"
	"gorm.io/gorm"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *videorpc.RegisterRequest) (*videorpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.UserInfo

	if err := user.FindUserByPhone(mysql.DB, in.PhoneNum); err == nil {
		return nil, errors.New("手机号码已存在,可直接登录")
	}
	result, _ := cache.Rdb.Get(l.ctx, "smsCode"+in.PhoneNum).Result()
	if result != in.SmsCode {
		return nil, errors.New("验证码不正确")
	}
	users := mysql.UserInfo{
		Model:    gorm.Model{},
		PhoneNum: in.PhoneNum,
		Pwd:      pkg.Md5(in.Pwd),
		NickName: fmt.Sprintf("游客_%d", rand.Intn(10000)),
		Url:      "alengitdmg.jpg",
	}

	if err := users.CreateUsers(mysql.DB); err != nil {
		return nil, errors.New("注册失败")
	}
	return &videorpc.RegisterResponse{
		UserId: int64(users.ID),
	}, nil
}
